package com.dj.dormitory.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dj.dormitory.commonutils.Result;
import com.dj.dormitory.entity.Org;
import com.dj.dormitory.service.OrgService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author DJ同学
 * @since 2021-01-24
 */
@RestController
@RequestMapping("/org")
public class OrgController {

    @Autowired
    private OrgService orgService;

    @PostMapping("tree")
    //传入当前的id 找到下面的
    public Result list(@RequestBody Map map){
        if(map.size()==0){//处理初始化的时候，没有id
            map.put("id",0);
        }
        Integer id = (Integer) map.get("id");

        QueryWrapper<Org> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);

        List<Org> list = orgService.list(wrapper);
        for(Org one : list){
            if(one.getType()==4)
                    one.setIsParent(false);
        }
        return Result.ok().data("tree",list);
    }
    @PostMapping("add")
    public Result add(@RequestBody Org org){
        if(org.getParentId()==null){
            org.setParentId(0);
        }
        boolean save = orgService.save(org);
        return save? Result.ok().message("组织添加成功"):Result.error().message("组织添加失败");
    }
    @PostMapping("edit")
    public Result edit(@RequestBody Org org){
        boolean edit = orgService.updateById(org);
        return edit? Result.ok().message("组织修改成功"):Result.error().message("组织修改失败");
    }
    @DeleteMapping("deleteOne/{id}")
    public Result delete(@PathVariable String id){
        //判断是不是叶子节点 是叶子节点才进行删除
        QueryWrapper<Org> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Org> list = orgService.list(wrapper);
        if(list.size()!=0){
            return Result.error().message("请选择叶子节点进行删除");
        }else{
            boolean delete = orgService.removeById(id);
            return delete ? Result.ok().message("组织删除成功"):Result.error().message("组织删除失败");
        }
    }
    //通过id获得org信息
    @RequestMapping("one")
    public Result one(@RequestParam(value = "id") String id){
        Org org = orgService.getById(Integer.parseInt(id));
        return Result.ok().data("org",org);
    }

    //获得所有班级
    @RequestMapping("getClasses")
    public Result getClasses(){
        QueryWrapper<Org> wrapper = new QueryWrapper<>();
        wrapper.eq("type",4);
        List<Org> list = orgService.list(wrapper);
        return Result.ok().data("classes",list);
    }
}

